{% extends "base.html" %}

{% block title %}密码管理 - {{ app_name }}{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-key me-2"></i>
                密码管理
            </h2>
            <div>
                {% if user.role == 'admin' %}
                <a href="/admin" class="btn btn-outline-secondary me-2">
                    <i class="fas fa-arrow-left me-2"></i>返回后台
                </a>
                {% else %}
                <a href="/home" class="btn btn-outline-secondary me-2">
                    <i class="fas fa-arrow-left me-2"></i>返回首页
                </a>
                {% endif %}
                <button type="button" class="btn btn-info me-2" data-bs-toggle="modal" data-bs-target="#addPasswordModal">
                    <i class="fas fa-plus me-2"></i>
                    添加密码
                </button>
                <button type="button" class="btn btn-warning me-2" data-bs-toggle="modal" data-bs-target="#importPasswordModal">
                    <i class="fas fa-upload me-2"></i>
                    导入数据
                </button>
                <button type="button" class="btn btn-success" onclick="exportPasswords()">
                    <i class="fas fa-download me-2"></i>
                    导出数据
                </button>
            </div>
        </div>
        
        <!-- 搜索和筛选 -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-5">
                        <label for="searchInput" class="form-label">搜索</label>
                        <input type="text" class="form-control" id="searchInput" placeholder="搜索URL、账号或用户名...">
                    </div>
                    <div class="col-md-5">
                        <label for="dateFilter" class="form-label">创建时间</label>
                        <select class="form-select" id="dateFilter">
                            <option value="">所有时间</option>
                            <option value="today">今天</option>
                            <option value="week">最近一周</option>
                            <option value="month">最近一月</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-grid">
                            <button type="button" class="btn btn-primary" onclick="applyFilters()">
                                <i class="fas fa-search me-2"></i>筛选
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 密码列表 -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                <h5 class="mb-0">密码列表</h5>
                <span class="badge bg-primary" id="totalCount">0</span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="passwordsTable">
                        <thead class="table-light">
                            <tr>
                                <th>网站/URL</th>
                                <th>账号</th>
                                <th>描述</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 数据将通过JavaScript加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 查看密码模态框 -->
<div class="modal fade" id="viewPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-eye me-2"></i>
                    查看密码详情
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label fw-bold">网站/URL</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="viewUrl" readonly>
                        <button class="btn btn-outline-primary" type="button" onclick="openUrl()">
                            <i class="fas fa-external-link-alt"></i>
                        </button>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">账号</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="viewAccount" readonly>
                        <button class="btn btn-outline-secondary" type="button" onclick="copyField('viewAccount')">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">密码</label>
                    <div class="input-group">
                        <input type="password" class="form-control font-monospace" id="viewPassword" readonly>
                        <button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('viewPassword')">
                            <i class="fas fa-eye" id="viewPasswordIcon"></i>
                        </button>
                        <button class="btn btn-outline-success" type="button" onclick="copyField('viewPassword')">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-bold">描述</label>
                    <textarea class="form-control" id="viewDescription" rows="3" readonly></textarea>
                </div>
                <div class="row">
                    <div class="col-6">
                        <label class="form-label fw-bold">所属用户</label>
                        <input type="text" class="form-control" id="viewUser" readonly>
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold">创建时间</label>
                        <input type="text" class="form-control" id="viewCreatedAt" readonly>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="createShare()">
                    <i class="fas fa-share-alt me-2"></i>
                    创建分享
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deletePasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    确认删除
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个密码记录吗？</p>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>警告：</strong>此操作将同时删除相关的分享记录和访问日志，且不可恢复！
                </div>
                <div id="deletePasswordInfo" class="bg-light p-3 rounded">
                    <!-- 密码信息将在这里显示 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDeletePassword()">
                    <i class="fas fa-trash me-2"></i>
                    确认删除
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 添加密码模态框 -->
<div class="modal fade" id="addPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-plus me-2"></i>
                    添加新密码
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addPasswordForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="addUrl" class="form-label">网站/URL *</label>
                        <input type="url" class="form-control" id="addUrl" name="url" required placeholder="">
                    </div>
                    <div class="mb-3">
                        <label for="addAccount" class="form-label">账号 *</label>
                        <input type="text" class="form-control" id="addAccount" name="account" required placeholder="">
                    </div>
                    <div class="mb-3">
                        <label for="addPassword" class="form-label">密码 *</label>
                        <div class="input-group">
                            <input type="password" class="form-control font-monospace" id="addPassword" name="password" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('addPassword')">
                                <i class="fas fa-eye" id="addPasswordIcon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="addDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="addDescription" name="description" rows="3" placeholder=""></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>
                        保存密码
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑密码模态框 -->
<div class="modal fade" id="editPasswordModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-edit me-2"></i>
                    编辑密码
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editPasswordForm">
                <div class="modal-body">
                    <input type="hidden" id="editPasswordId" name="password_id">
                    <div class="mb-3">
                        <label for="editUrl" class="form-label">网站/URL *</label>
                        <input type="url" class="form-control" id="editUrl" name="url" required>
                    </div>
                    <div class="mb-3">
                        <label for="editAccount" class="form-label">账号 *</label>
                        <input type="text" class="form-control" id="editAccount" name="account" required>
                    </div>
                    <div class="mb-3">
                        <label for="editPasswordField" class="form-label">密码 *</label>
                        <div class="input-group">
                            <input type="password" class="form-control font-monospace" id="editPasswordField" name="password" required>
                            <button class="btn btn-outline-secondary" type="button" onclick="togglePasswordVisibility('editPasswordField')">
                                <i class="fas fa-eye" id="editPasswordFieldIcon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="editDescriptionField" class="form-label">描述</label>
                        <textarea class="form-control" id="editDescriptionField" name="description" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-2"></i>
                        保存更改
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 创建分享模态框 -->
<div class="modal fade" id="createShareModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-share-alt me-2"></i>
                    创建密码分享
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createShareForm">
                <div class="modal-body">
                    <div class="alert alert-info border-0">
                        <div class="d-flex">
                            <div class="flex-shrink-0">
                                <i class="fas fa-info-circle"></i>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h6 class="alert-heading">分享说明</h6>
                                <small>
                                    创建分享链接后，任何拥有链接的人都可以查看密码信息。为了安全，建议设置访问密码和有效期。
                                </small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="shareExpiresHours" class="form-label">有效期（小时）</label>
                        <select class="form-select" id="shareExpiresHours" name="expires_hours">
                            <option value="1">1小时</option>
                            <option value="6">6小时</option>
                            <option value="24" selected>24小时</option>
                            <option value="72">3天</option>
                            <option value="168">7天</option>
                            <option value="0">永不过期</option>
                        </select>
                        <div class="form-text">链接过期后将无法访问</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="shareAccessPassword" class="form-label">访问密码 <span class="text-muted">(可选)</span></label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="shareAccessPassword" name="access_password" placeholder="留空表示无需密码">
                            <button class="btn btn-outline-secondary" type="button" onclick="toggleSharePasswordVisibility()">
                                <i class="fas fa-eye" id="sharePasswordIcon"></i>
                            </button>
                            <button class="btn btn-outline-primary" type="button" onclick="generateSharePassword()">
                                <i class="fas fa-random"></i>
                            </button>
                        </div>
                        <div class="form-text">设置访问密码可以增加安全性，访问者需要输入密码才能查看内容</div>
                    </div>
                    
                    <div class="alert alert-warning border-0">
                        <div class="d-flex">
                            <div class="flex-shrink-0">
                                <i class="fas fa-exclamation-triangle"></i>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h6 class="alert-heading">安全提醒</h6>
                                <ul class="mb-0 small">
                                    <li>分享链接包含敏感信息，请谨慎分享</li>
                                    <li>建议通过安全渠道（如加密聊天）发送链接</li>
                                    <li>如设置访问密码，请单独告知访问者</li>
                                    <li>不再需要时请及时删除分享记录</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="confirmCreateShare()">
                        <i class="fas fa-share-alt me-2"></i>
                        创建分享链接
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 导入密码模态框 -->
<div class="modal fade" id="importPasswordModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-upload me-2"></i>
                    导入密码数据
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <h6><i class="fas fa-info-circle me-2"></i>导入说明</h6>
                    <ul class="mb-0 small">
                        <li>支持CSV和Excel格式文件（.csv, .xlsx, .xls）</li>
                        <li>文件格式：URL | 账号 | 密码 | 描述</li>
                        <li>第一行为标题行，将被忽略</li>
                        <li>URL、账号、密码、为必填项</li>
                    </ul>
                </div>
                
                <div class="mb-3">
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-success btn-sm" onclick="downloadPasswordTemplate()">
                            <i class="fas fa-download me-2"></i>下载导入模板
                        </button>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="downloadSampleData()">
                            <i class="fas fa-file-excel me-2"></i>下载示例数据
                        </button>
                    </div>
                    <small class="text-muted">建议先下载模板，按格式填写数据后再导入</small>
                </div>
                
                <form id="importPasswordForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="importPasswordFile" class="form-label">选择Excel文件</label>
                        <input type="file" class="form-control" id="importPasswordFile" name="file" accept=".csv,.xlsx,.xls" required>
                        <div class="form-text">支持 .csv, .xlsx 和 .xls 格式</div>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="skipPasswordDuplicates" name="skip_duplicates" checked>
                            <label class="form-check-label" for="skipPasswordDuplicates">
                                跳过重复的URL+账号组合
                            </label>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">文件格式要求：</label>
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered">
                                <thead class="table-light">
                                    <tr>
                                        <th>A列: URL</th>
                                        <th>B列: 账号</th>
                                        <th>C列: 密码</th>
                                        <th>E列: 描述</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="small text-muted">
                                        <td>https://guzian.cn:810</td>
                                        <td>user@example.com</td>
                                        <td>password123</td>
                                        <td>示例网站</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </form>
                
                <div id="importPasswordProgress" class="d-none">
                    <div class="progress mb-3">
                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                    </div>
                    <div id="importPasswordStatus"></div>
                </div>
                
                <div id="importPasswordResult" class="d-none">
                    <h6>导入结果：</h6>
                    <div id="importPasswordSummary"></div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="startPasswordImport()" id="importPasswordBtn">
                    <i class="fas fa-upload me-2"></i>
                    开始导入
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let allPasswords = [];
let filteredPasswords = [];
let currentPasswordId = null;

$(document).ready(function() {
    loadPasswords();
    loadUsers();
    
    // 搜索和筛选事件
    $('#searchInput, #userFilter, #dateFilter').on('input change', function() {
        applyFilters();
    });
    
    // 添加密码表单提交
    $('#addPasswordForm').on('submit', function(e) {
        e.preventDefault();
        addPassword();
    });
    
    // 编辑密码表单提交
    $('#editPasswordForm').on('submit', function(e) {
        e.preventDefault();
        updatePassword();
    });
    
    // 模态框显示时加载用户列表
    $('#addPasswordModal, #editPasswordModal').on('show.bs.modal', function() {
        loadUsersForSelect();
    });
});

$(document).ready(function() {
    loadPasswords();
    loadUsers();
    
    // 搜索框实时搜索
    $('#searchInput').on('input', App.Utils.debounce(applyFilters, 300));
});

function loadPasswords() {
    $.ajax({
        url: '/api/passwords',
        method: 'GET',
        success: function(response) {
            // 确保response和passwords字段存在
            allPasswords = response && response.passwords ? response.passwords : [];
            filteredPasswords = [...allPasswords];
            renderPasswordsTable();
            updateTotalCount();
        },
        error: function(xhr) {
            console.error('加载密码列表失败:', xhr);
            App.Utils.showNotification('加载密码列表失败', 'error');
        }
    });
}

function loadUsers() {
    $.ajax({
        url: '/api/users',
        method: 'GET',
        success: function(response) {
            const userFilter = $('#userFilter');
            userFilter.empty().append('<option value="">所有用户</option>');
            
            response.users.forEach(function(user) {
                userFilter.append(`<option value="${user.id}">${user.username}</option>`);
            });
        },
        error: function(xhr) {
            console.error('加载用户列表失败:', xhr);
        }
    });
}

function loadUsersForSelect() {
    return $.ajax({
        url: '/api/users',
        method: 'GET',
        success: function(response) {
            const addUserId = $('#addUserId');
            const editUserId = $('#editUserId');
            
            // 清空并添加默认选项
            addUserId.empty().append('<option value="">请选择用户</option>');
            editUserId.empty().append('<option value="">请选择用户</option>');
            
            response.users.forEach(function(user) {
                addUserId.append(`<option value="${user.id}">${user.username}</option>`);
                editUserId.append(`<option value="${user.id}">${user.username}</option>`);
            });
        },
        error: function(xhr) {
            console.error('加载用户列表失败:', xhr);
            App.Utils.showNotification('加载用户列表失败', 'error');
        }
    });
}

function renderPasswordsTable() {
    const tbody = $('#passwordsTable tbody');
    tbody.empty();
    
    if (filteredPasswords.length === 0) {
        tbody.append(`
            <tr>
                <td colspan="6" class="text-center text-muted py-4">
                    <i class="fas fa-key fa-2x mb-2"></i><br>
                    暂无密码数据
                </td>
            </tr>
        `);
        return;
    }
    
    filteredPasswords.forEach(function(password) {
        const createdAt = App.Utils.formatDateTime(password.created_at);
        const shortUrl = password.url.length > 30 ? password.url.substring(0, 30) + '...' : password.url;
        const shortDescription = password.description ? 
            (password.description.length > 20 ? password.description.substring(0, 20) + '...' : password.description) : 
            '-';
        
        tbody.append(`
            <tr>

                <td>
                    <div class="d-flex align-items-center">
                        <i class="fas fa-globe text-primary me-2"></i>
                        <span title="${password.url}">${shortUrl}</span>
                    </div>
                </td>

                <td>
                    <span class="badge bg-info">${password.account}</span>
                </td>
                <td title="${password.description || ''}">${shortDescription}</td>
                <td>${createdAt}</td>
                <td>
                    <div class="btn-group btn-group-sm" role="group">
                        <button class="btn btn-outline-primary" onclick="viewPassword(${password.id})" title="查看详情">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="btn btn-outline-warning" onclick="editPassword(${password.id})" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-outline-danger" onclick="deletePassword(${password.id})" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `);
    });
}

function applyFilters() {
    const searchTerm = $('#searchInput').val().toLowerCase();
    const userFilter = $('#userFilter').val();
    const dateFilter = $('#dateFilter').val();
    
    filteredPasswords = allPasswords.filter(function(password) {
        // 搜索过滤
        if (searchTerm) {
            const searchFields = [
                password.url.toLowerCase(),
                password.account.toLowerCase(),
                password.user_name.toLowerCase(),
                (password.description || '').toLowerCase()
            ];
            if (!searchFields.some(field => field.includes(searchTerm))) {
                return false;
            }
        }
        
        // 用户过滤
        if (userFilter && password.user_name !== userFilter) {
            return false;
        }
        
        // 日期过滤
        if (dateFilter) {
            const createdDate = new Date(password.created_at);
            const now = new Date();
            
            switch (dateFilter) {
                case 'today':
                    if (createdDate.toDateString() !== now.toDateString()) {
                        return false;
                    }
                    break;
                case 'week':
                    const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
                    if (createdDate < weekAgo) {
                        return false;
                    }
                    break;
                case 'month':
                    const monthAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
                    if (createdDate < monthAgo) {
                        return false;
                    }
                    break;
            }
        }
        
        return true;
    });
    
    renderPasswordsTable();
    updateTotalCount();
}

function updateTotalCount() {
    $('#totalCount').text(filteredPasswords.length);
}

function viewPassword(passwordId) {
    const password = allPasswords.find(p => p.id === passwordId);
    if (!password) return;
    
    currentPasswordId = passwordId;
    
    $('#viewUrl').val(password.url);
    $('#viewAccount').val(password.account);
    $('#viewPassword').val('••••••••'); // 不直接显示密码
    $('#viewDescription').val(password.description || '');
    $('#viewUser').val(password.user_name);
    $('#viewCreatedAt').val(App.Utils.formatDateTime(password.created_at));
    
    // 获取实际密码
    $.ajax({
        url: `/api/passwords/${passwordId}/detail`,
        method: 'GET',
        success: function(response) {
            $('#viewPassword').val(response.password.password);
        },
        error: function(xhr) {
            console.error('获取密码详情失败:', xhr);
        }
    });
    
    $('#viewPasswordModal').modal('show');
}

function deletePassword(passwordId) {
    const password = allPasswords.find(p => p.id === passwordId);
    if (!password) return;
    
    currentPasswordId = passwordId;
    
    $('#deletePasswordInfo').html(`
        <div><strong>网站：</strong> ${password.url}</div>
        <div><strong>账号：</strong> ${password.account}</div>
        <div><strong>用户：</strong> ${password.user_name}</div>
        <div><strong>创建时间：</strong> ${App.Utils.formatDateTime(password.created_at)}</div>
    `);
    
    $('#deletePasswordModal').modal('show');
}

function confirmDeletePassword() {
    if (!currentPasswordId) return;
    
    $.ajax({
        url: `/api/passwords/${currentPasswordId}`,
        method: 'DELETE',
        success: function(response) {
            App.Utils.showNotification('密码删除成功', 'success');
            $('#deletePasswordModal').modal('hide');
            loadPasswords(); // 重新加载列表
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.detail || '删除失败';
            App.Utils.showNotification(error, 'error');
        }
    });
}

function togglePasswordVisibility(fieldId) {
    const field = document.getElementById(fieldId);
    const icon = document.getElementById(fieldId + 'Icon');
    
    if (field.type === 'password') {
        field.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        field.type = 'password';
        icon.className = 'fas fa-eye';
    }
}

function copyField(fieldId) {
    const field = document.getElementById(fieldId);
    App.Utils.copyToClipboard(field.value, function(success) {
        if (success) {
            App.Utils.showNotification('已复制到剪贴板', 'success', 1000);
        } else {
            App.Utils.showNotification('复制失败', 'error');
        }
    });
}

function openUrl() {
    const url = $('#viewUrl').val();
    if (url) {
        window.open(url, '_blank');
    }
}

function createShare() {
    if (!currentPasswordId) {
        App.Utils.showAlert('请先选择一个密码记录', 'warning');
        return;
    }
    
    // 显示分享设置模态框
    $('#createShareModal').modal('show');
}

function confirmCreateShare() {
    const expiresHours = parseInt($('#shareExpiresHours').val()) || 0;
    const accessPassword = $('#shareAccessPassword').val().trim();
    
    $.ajax({
        url: '/api/shares',
        method: 'POST',
        data: {
            password_id: currentPasswordId,
            expires_hours: expiresHours,
            access_password: accessPassword
        },
        success: function(response) {
            // 构建分享链接（使用相对路径）
            const shareUrl = window.location.origin + response.share_url;
            const accessPassword = $('#shareAccessPassword').val().trim();
            
            // 准备分享信息
            let shareInfo = `分享链接创建成功！\n\n`;
            shareInfo += `🔗 分享链接：${shareUrl}\n`;
            
            if (accessPassword) {
                shareInfo += `🔑 访问密码：${accessPassword}\n`;
            }
            if (response.expires_at) {
                const expiresDate = new Date(response.expires_at);
                copyContent += `⏰ 过期时间：${expiresDate.toLocaleString('zh-CN')}\n`;
            }
            
            shareInfo += `\n⚠️ 安全提醒：请通过安全渠道发送此信息`;
            
            // 显示成功消息
            if (typeof App !== 'undefined' && App.Utils && App.Utils.showNotification) {
                App.Utils.showNotification('分享创建成功！', 'success');
            }
            
            // 显示详细信息
            alert(shareInfo);
            
            // 尝试复制到剪贴板
            if (navigator.clipboard) {
                navigator.clipboard.writeText(shareInfo).then(function() {
                    if (typeof App !== 'undefined' && App.Utils && App.Utils.showNotification) {
                        App.Utils.showNotification('分享链接已复制到剪贴板', 'info');
                    }
                }).catch(function() {
                    console.log('复制到剪贴板失败');
                });
            }
            
            $('#createShareModal').modal('hide');
            $('#viewPasswordModal').modal('hide');
            
            // 重置表单
            if (document.getElementById('createShareForm')) {
                document.getElementById('createShareForm').reset();
            }
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.detail || '创建分享失败';
            App.Utils.showAlert(error, 'error');
        }
    });
}

function exportPasswords() {
    // 导出密码数据为CSV格式
    if (filteredPasswords.length === 0) {
        App.Utils.showNotification('没有数据可导出', 'warning');
        return;
    }
    
    // 根据用户角色选择不同的导出API
    var exportUrl = "{% if user.role == 'admin' %}/api/export/passwords{% else %}/api/user/export/passwords{% endif %}";
    window.open(exportUrl, '_blank');
}

function generateCSV(data) {
    const headers = ['ID', '网站/URL', '账号', '描述', '创建时间'];
    const csvRows = [headers.join(',')];
    
    data.forEach(function(password) {
        const row = [
            password.id,
            `"${password.url}"`,
            `"${password.account}"`,
            `"${password.description || ''}"`,
            `"${App.Utils.formatDateTime(password.created_at)}"`
        ];
        csvRows.push(row.join(','));
    });
    
    return csvRows.join('\n');
}

function downloadCSV(content, filename) {
    const blob = new Blob(['\ufeff' + content], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    
    if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
}

// 添加密码功能
function addPassword() {
    const formData = new FormData($('#addPasswordForm')[0]);
    
    $.ajax({
        url: '/api/passwords',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            App.Utils.showAlert(response.message, 'success');
            $('#addPasswordModal').modal('hide');
            $('#addPasswordForm')[0].reset();
            loadPasswords();
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.detail || '添加密码失败';
            App.Utils.showAlert(error, 'error');
        }
    });
}

// 编辑密码功能
function editPassword(passwordId) {
    // 获取密码信息
    $.ajax({
        url: `/api/passwords/${passwordId}/detail`,
        method: 'GET',
        success: function(response) {
            const passwordData = response.password;
            if (passwordData) {
                $('#editPasswordId').val(passwordId);
                $('#editUrl').val(passwordData.url);
                $('#editAccount').val(passwordData.account);
                $('#editPasswordField').val(passwordData.password);
                $('#editDescriptionField').val(passwordData.description || '');
                $('#editPasswordModal').modal('show');
            }
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.detail || '获取密码信息失败';
            App.Utils.showAlert(error, 'error');
        }
    });
}

function updatePassword() {
    const passwordId = $('#editPasswordId').val();
    const formData = new FormData($('#editPasswordForm')[0]);

    $.ajax({
        url: `/api/passwords/${passwordId}`,
        method: 'PUT',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            App.Utils.showAlert(response.message, 'success');
            $('#editPasswordModal').modal('hide');
            $('#editPasswordForm')[0].reset();
            loadPasswords();
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.detail || '更新密码失败';
            App.Utils.showAlert(error, 'error');
        }
    });
}

// 导入密码功能
function startPasswordImport() {
    const fileInput = $('#importPasswordFile')[0];
    const file = fileInput.files[0];
    
    if (!file) {
        App.Utils.showAlert('请选择要导入的CSV文件', 'warning');
        return;
    }
    
    const fileName = file.name.toLowerCase();
    if (!fileName.endsWith('.csv') && !fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
        App.Utils.showAlert('请选择CSV或Excel格式的文件', 'warning');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('skip_duplicates', $('#skipPasswordDuplicates').is(':checked'));
    
    // 显示进度条
    $('#importPasswordProgress').removeClass('d-none');
    $('#importPasswordResult').addClass('d-none');
    $('#importPasswordBtn').prop('disabled', true);
    
    // 模拟进度更新
    let progress = 0;
    const progressInterval = setInterval(function() {
        progress += Math.random() * 20;
        if (progress > 90) progress = 90;
        $('.progress-bar').css('width', progress + '%');
        $('#importPasswordStatus').text('正在处理文件...');
    }, 200);
    
    $.ajax({
        url: '/api/import/passwords',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            clearInterval(progressInterval);
            $('.progress-bar').css('width', '100%');
            $('#importPasswordStatus').text('导入完成');
            
            // 显示结果
            setTimeout(function() {
                $('#importPasswordProgress').addClass('d-none');
                $('#importPasswordResult').removeClass('d-none');
                
                const summary = `
                    <div class="alert alert-success">
                        <div class="row">
                            <div class="col-sm-6">成功导入：<strong>${response.success_count}</strong> 个密码</div>
                            <div class="col-sm-6">跳过重复：<strong>${response.skipped_count}</strong> 个密码</div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-sm-6">失败记录：<strong>${response.error_count}</strong> 个</div>
                            <div class="col-sm-6">总计处理：<strong>${response.total_count}</strong> 个</div>
                        </div>
                    </div>
                `;
                
                if (response.errors && response.errors.length > 0) {
                    const errorList = response.errors.map(error => 
                        `<li>第${error.row}行: ${error.message}</li>`
                    ).join('');
                    summary += `
                        <div class="alert alert-warning">
                            <h6>错误详情：</h6>
                            <ul class="mb-0">${errorList}</ul>
                        </div>
                    `;
                }
                
                $('#importPasswordSummary').html(summary);
                
                if (response.success_count > 0) {
                    loadPasswords(); // 重新加载密码列表
                }
            }, 500);
        },
        error: function(xhr) {
            clearInterval(progressInterval);
            $('#importPasswordProgress').addClass('d-none');
            
            const error = xhr.responseJSON?.detail || '导入失败';
            App.Utils.showAlert(error, 'error');
        },
        complete: function() {
            $('#importPasswordBtn').prop('disabled', false);
        }
    });
}

// 分享密码相关函数
function toggleSharePasswordVisibility() {
    const field = document.getElementById('shareAccessPassword');
    const icon = document.getElementById('sharePasswordIcon');
    
    if (field.type === 'password') {
        field.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        field.type = 'password';
        icon.className = 'fas fa-eye';
    }
}

function generateSharePassword() {
    // 生成8位随机密码
    const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
    let password = '';
    for (let i = 0; i < 8; i++) {
        password += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    
    $('#shareAccessPassword').val(password);
    
    // 显示密码
    const field = document.getElementById('shareAccessPassword');
    const icon = document.getElementById('sharePasswordIcon');
    field.type = 'text';
    icon.className = 'fas fa-eye-slash';
    
    // 使用兼容的提示方式
    if (typeof App !== 'undefined' && App.Utils && App.Utils.showAlert) {
        App.Utils.showAlert('已生成访问密码，请记住并告知访问者', 'info');
    } else {
        alert('已生成访问密码，请记住并告知访问者');
    }
}

// 下载导入模板
function downloadPasswordTemplate() {
    window.open('/api/export/password_template', '_blank');
}

// 下载示例数据
function downloadSampleData() {
    window.open('/api/export/password_sample', '_blank');
}
</script>
{% endblock %}